package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Sets;
import com.zhijian.medical.dao.local.SangerCxqMapper;
import com.zhijian.medical.entity.dto.SangerHskzyqInsideDto;
import com.zhijian.medical.entity.dto.SangerHskzyqOutsideDto;
import com.zhijian.medical.entity.dto.SangerSjpzqPcrDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Sanger;
import com.zhijian.medical.entity.po.SangerCxq;
import com.zhijian.medical.entity.po.SangerSjpzq;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.SangerCxqSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerCxqSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.SangerCxqVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.SangerStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 一代测序-测序区（毛细管电泳）业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-16 15:44:47
 */
@Slf4j
@Service
public class SangerCxqServiceImpl implements SangerCxqService {

    @Autowired
    private SangerCxqMapper mapper;

    @Autowired
    private SangerSjpzqService sangerSjpzqService;

    @Autowired
    private SangerService sangerService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public SangerCxq selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SangerCxq selectBySangerId(Long sangerId) {
        return mapper.selectBySangerId(sangerId);
    }

    @Override
    public SangerCxqVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public SangerCxqVo selectVoBySangerId(Long sangerId) {
        SangerCxqVo sangerCxqVo = mapper.selectVoBySangerId(sangerId);
        if (Objects.isNull(sangerCxqVo)) {
            return null;
        }
        Sanger sanger = sangerService.selectById(sangerId);
        if (Objects.isNull(sanger)) {
            return null;
        }
        sangerCxqVo.setResult(sanger.getStatus() > SangerStatusEnum.CXQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sangerCxqVo.setResultStr(sanger.getStatus() > SangerStatusEnum.CXQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String lcbbbshfxwzData = sangerCxqVo.getLcbbbshfxwzData();
        if (StringUtils.isNotBlank(lcbbbshfxwzData)) {
            sangerCxqVo.setLcbbbshfxwzDataList(JsonUtil.toArray(lcbbbshfxwzData, SangerHskzyqOutsideDto.class));
        }
        return sangerCxqVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(SangerCxq sangerCxq) {
        Date now = new Date();
        sangerCxq.setCreateTime(now);
        sangerCxq.setUpdateTime(now);
        sangerCxq.setSytmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerCxq.setAzfzzsop010fzzsop06(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerCxq.setCxy(StatusEnum.NORMAL.getCode().byteValue());
        sangerCxq.setQjwhcxy(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerCxq.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(sangerCxq) > 0 ? sangerCxq.getId() : 0L;
    }

    @Override
    public boolean update(SangerCxq sangerCxq) {
        Date now = new Date();
        sangerCxq.setUpdateTime(now);
        return mapper.updateByPrimaryKey(sangerCxq) != 0;
    }

    @Override
    public Integer count(SangerCxqSearchVo sangerCxqSearchVo) {
        return mapper.count(sangerCxqSearchVo);
    }

    @Override
    public List<SangerCxqVo> selectList(SangerCxqSearchVo sangerCxqSearchVo) {
        return mapper.selectList(sangerCxqSearchVo);
    }

    @Override
    public Page<SangerCxqVo> selectPage(SangerCxqSearchVo sangerCxqSearchVo) {
        //先直接查总数
        int count = count(sangerCxqSearchVo);
        //分页
        Page<SangerCxqVo> page = new Page<>(true, count, sangerCxqSearchVo.getPageNum(), sangerCxqSearchVo.getPageSize());
        sangerCxqSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SangerCxqVo> responseVos = this.selectList(sangerCxqSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(SangerCxqSaveOrUpdateVo sangerCxqSaveOrUpdateVo) {
        Long sangerId = sangerCxqSaveOrUpdateVo.getSangerId();
        Sanger sanger = sangerService.selectById(sangerId);
        AssertUtil.notNull(sanger, "此实验不存在或者已被删除");
        if (sanger.getStatus() < SangerStatusEnum.SJFX.getCode().byteValue()) {
            //将实验的状态修改
            sangerService.updateByPrimaryKeySelective(Sanger.builder()
                    .id(sangerId)
                    .status(SangerStatusEnum.SJFX.getCode().byteValue())
                    .build());
        }
        SangerCxq oldSangerCxq = this.selectBySangerId(sangerId);
        List<SangerHskzyqOutsideDto> sangerHskzyqSaveOrUpdateVoDataList = sangerCxqSaveOrUpdateVo.getLcbbbshfxwzDataList();
        if (CollectionUtil.isNotEmpty(sangerHskzyqSaveOrUpdateVoDataList)) {
            //如果传了表格数据，前端只会传编号，要把编号对应的分子病理号查出来，也就是去试剂配置区里查
            SangerSjpzq sangerSjpzq = sangerSjpzqService.selectBySangerId(sangerId);
            AssertUtil.notNull(sangerSjpzq, "还未完成试剂配置区");
            String pcrData = sangerSjpzq.getPcrData();
            AssertUtil.check(StringUtils.isBlank(pcrData), "还未完成试剂配置区-PCR反应液分装至各反应管，反应编号及检测项目");
            //试剂配置区的PCR的数据
            List<SangerSjpzqPcrDto> sangerSjpzqPcrDtoList = JsonUtil.toArray(pcrData, SangerSjpzqPcrDto.class);

            Set<Integer> set = Sets.newHashSet();
            sangerHskzyqSaveOrUpdateVoDataList.forEach(sangerHskzyqOutsideDto -> {
                List<List<SangerHskzyqInsideDto>> sangerHskzyqOutsideDtoData = sangerHskzyqOutsideDto.getData();
                if (CollectionUtil.isNotEmpty(sangerHskzyqOutsideDtoData)) {
                    sangerHskzyqOutsideDtoData.forEach(sangerHskzyqInsideDtos -> {
                        if (CollectionUtil.isNotEmpty(sangerHskzyqInsideDtos)) {
                            sangerHskzyqInsideDtos.stream().filter(s -> Objects.nonNull(s.getBh())).forEach(sangerHskzyqInsideDto -> {
                                //编号
                                Integer bh = sangerHskzyqInsideDto.getBh();
                                AssertUtil.check(!set.add(bh), "反应孔数据不允许有重复编号");
                                //筛选出编号一样的数据
                                SangerSjpzqPcrDto sangerSjpzqPcrDto = sangerSjpzqPcrDtoList.stream().filter(s -> s.getNumber().equals(bh)).findFirst().orElse(null);
                                sangerHskzyqInsideDto.setFzblh(Objects.nonNull(sangerSjpzqPcrDto) ? String.format("%s-%s-%s", sangerSjpzqPcrDto.getFzblh(), sangerSjpzqPcrDto.getProject(), sangerSjpzqPcrDto.getTurn()) : null);
                            });
                        }
                    });
                }
            });
            sangerCxqSaveOrUpdateVo.setLcbbbshfxwzData(JsonUtil.toString(sangerHskzyqSaveOrUpdateVoDataList));
        }
        SangerCxq dbParam = new SangerCxq();
        BeanUtils.copyProperties(sangerCxqSaveOrUpdateVo, dbParam);
        if (Objects.isNull(oldSangerCxq)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldSangerCxq.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .experimentProcessId(sangerId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .op(String.format("%s%s-%s", sanger.getName(), sanger.getProcessNumber(), SangerStatusEnum.CXQ.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}